package com.lemon.core.web.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.URLUtil;
import cn.hutool.json.JSONUtil;
import com.lemon.core.base.constant.SecurityConstants;
import com.lemon.core.base.context.TenantContextHolder;
import com.lemon.core.base.context.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理异步线程请求头丢失问题
 *
 * @author pan
 * @since 2020-03-06
 */
@Slf4j
public class HeaderThreadLocalInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return HandlerInterceptor.super.preHandle(request, response, handler);
        }
        TenantContextHolder.setTenantId(request.getHeader(SecurityConstants.TENANT_ID_KEY));
        UserContextHolder.setUserId(Convert.toLong(request.getHeader(SecurityConstants.USER_ID_KEY)));
        UserContextHolder.setUsername(request.getHeader(SecurityConstants.USER_NAME_KEY));
        UserContextHolder.setRoles(JSONUtil.toList(URLUtil.decode(request.getHeader(SecurityConstants.ROLES_KEY)), String.class));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContextHolder.clear();
        TenantContextHolder.clear();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
